package com.zzyl.serve.service.impl;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.DeviceReportDataVo;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 * 
 * @author liusm
 * @date 2025-08-22
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //1.从物联网平台查询所有产品列表
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() !=200){
            throw new BaseException("物联网接口-同步设备列表失败");
        }

        //将产品列表缓存到Redis中
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, JSONUtil.toJsonStr(response.getProducts()));
    }

    /**
     * 查询所有产品列表
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //1.从Redis中查询产品列表
        String str = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        //2.如果查询不到,就返回一个空集合
        if (StringUtils.isEmpty(str)){
            return Collections.emptyList();
        }
        //3.将Redis中的json数组转换成ProductVo列表并返回
        return JSONUtil.toList(str,ProductVo.class);
    }

    /**
     * 注册设备
     * @param deviceDto
     */
    @Override
    public void register(DeviceDto deviceDto) {
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, deviceDto.getDeviceName());
        //判断设备标识码是否已存在
        if (count(wrapper)>0){
            throw new BaseException("设备标识码已存在,请重新输入");
        }
        //判断设备名称是否已存在
        wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId,deviceDto.getIotId());

        if (count(wrapper)>0){
            throw new BaseException("设备名称已存在,请重新输入");
        }
        //判断同一位置是否已存在
        wrapper=Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey,deviceDto.getProductKey())
                .eq(Device::getLocationType,deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType,deviceDto.getPhysicalLocationType())
                .eq(Device::getBindingLocation,deviceDto.getBindingLocation());
        if (count(wrapper)>0){
            throw new BaseException("该老人位置已绑定该产品,请重新选择");
        }
        //iot中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setProductId(deviceDto.getProductKey());
        body.setDeviceName(deviceDto.getDeviceName());
        body.setNodeId(deviceDto.getNodeId());
        //1.创建认证信息对象,

        // 1.1创建一个AuthInfo对象,用于存储设备的认证信息
        AuthInfo authInfo = new AuthInfo();

        //2生成密钥,

        // 2.1使用UUID工具生成一个随机字符串作为设备秘钥
        String secret = UUID.randomUUID().toString(true);
        //2.2将生成的秘钥设置到认证信息对象中
        authInfo.withSecret(secret);

        //3.设置设备认证信息

        //3.1将认证信息设置到设备对象中
        body.setAuthInfo(authInfo);
        //3.2将设备对象设置到请求体中
        request.setBody(body);

        //4.调用物联网平台接口

        //通过IoTDAClient客户端调用华为云物联网平台的设备添加接口
        AddDeviceResponse response = client.addDevice(request);

        //设备数据保存到数据库
        //属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //设备id,设备绑定状态
        device.setIotId(response.getDeviceId());
        //秘钥
        device.setSecret(secret);

        //在数据库中新增设备
        save(device);

    }

    @Override
    public DeviceDetailVo getInfo(String iotId) {
        //先从数据库中查询设备数据
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId);
        Device device = getOne(wrapper);
        if (device == null) {
            return null;
        }

        //再从华为云IoTDA中查询设备信息
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);

        //属性拷贝
        DeviceDetailVo vo = new DeviceDetailVo();
        BeanUtils.copyProperties(device, vo);
        vo.setBindingLocation(Long.parseLong(device.getBindingLocation()));
        vo.setDeviceStatus(response.getStatus());
        String activeTime = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTime)) {
            //将activeTime日期字符串值'2025-08-18T13:09:07.104Z'转换成LocalDateTime对象
            LocalDateTime dateTime = LocalDateTime.parse(activeTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
            //dateTime是0时区的时间，转换成北京东8区
            dateTime = dateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            vo.setActiveTime(dateTime);
        }

        return vo;

    }

    @Override
    public List<DeviceReportDataVo> queryDeviceProperties(String iotId) {
        //向物联网平台发请求 查询设备的影子信息
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        List<DeviceShadowData> shadow = response.getShadow();
        if (shadow == null || shadow.isEmpty()) {
            return Collections.emptyList();
        }

        //获取设备上报的数据
        Map<String,Object> properties = (Map<String, Object>) shadow.get(0).getReported().getProperties();

        //获取上报时间
        String eventTimeStr = shadow.get(0).getReported().getEventTime();
        LocalDateTime reportTime = LocalDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        LocalDateTime eventTime = reportTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();


        //封装结果
        List<DeviceReportDataVo> list = new ArrayList<>();
        properties.forEach((prop,value)->{
            DeviceReportDataVo vo = new DeviceReportDataVo();
            vo.setFunctionId(prop);
            vo.setEventTime(eventTime);
            vo.setValue(value);
            list.add(vo);
        });

        return list;
    }

    /**
     * 查询产品详情(报警规则模块使用)
     * @param productKey
     * @return
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode()!=200){
            throw new BaseException("物联网接口-查询产品信息失败");
        }
        return response.getServiceCapabilities();
    }


}

